package com.wzy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.wzy.entity.UserReadEntity;
import com.wzy.entity.UserWriteEntity;
import com.wzy.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wzy
 * @Date: 2022/1/25 10:12
 * @Description:
 */
@RequestMapping("/excel")
@RestController
public class ExcelController {

    @Autowired
    private ExcelService excelService;
    /**
     * 导出用户信息
     * @param response
     * @throws IOException
     */
    @GetMapping("/user/excelExport")
    public void excelExport(HttpServletResponse response) throws IOException {
        excelService.excelExport(response);
    }

    /**
     * 导入用户信息
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/user/excelImport")
    public String excelImport(@RequestParam("file") MultipartFile file) throws IOException {
        excelService.excelImport(file);
        return "success";
    }
    @PostMapping("/export")
    public String export() throws FileNotFoundException {
        List<UserWriteEntity> dataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            UserWriteEntity userEntity = new UserWriteEntity();
            userEntity.setName("张三" + i);
            userEntity.setAge(20 + i);
            userEntity.setTime(new Date(System.currentTimeMillis() + i));
            dataList.add(userEntity);
        }
        //定义文件输出位置
        FileOutputStream outputStream = new FileOutputStream(new File("D:/user.xlsx"));
        EasyExcel.write(outputStream, UserWriteEntity.class).sheet("用户信息").doWrite(dataList);
        return "导出成功";
    }
    @PostMapping("/read")
    public String read(@RequestParam("file") MultipartFile file) throws IOException {
        //同步读取文件内容
        List<UserReadEntity> list = EasyExcel.read(file.getInputStream()).head(UserReadEntity.class).sheet().doReadSync();
        System.out.println(JSONArray.toJSONString(list));
        return "读取成功";
    }


}
